package symbol;

import lexical.Word;
import midcode.MidcodeGenerator;

import java.util.ArrayList;

public class Function {
    public final Word ident;
    public final String returnType;
    public final ArrayList<Symbol> parameters = new ArrayList<>();
    public final ArrayList<Symbol> symbols = new ArrayList<>();
    private SymbolBlock block;
    private boolean returned = false;

    public Function(Word ident, String returnType) {
        this.ident = ident;
        this.returnType = returnType;
    }

    public String getName() {
        return ident.word;
    }

    public SymbolBlock getBlock() {
        return block;
    }

    public void setBlock(SymbolBlock block) {
        this.block = block;
    }

    public void addParameter(Symbol parameter) {
        parameters.add(parameter);
    }

    public void addSymbol(Symbol symbol) {
        symbols.add(symbol);
    }

    public void setReturned(boolean returned) {
        this.returned = returned;
    }

    public boolean haveReturn() {
        return (returnType.equals("int") && returned) || returnType.equals("void");
    }

    public Symbol searchSymbol(String name) {
        for (int i = symbols.size() - 1; i >= 0; i--) {
            if (symbols.get(i).getName().equals(name)) {
                return symbols.get(i);
            }
        }
        return null;
    }

    public Symbol searchParam(String val1) {
        for (Symbol symbol : parameters) {
            if (symbol.getName().equals(val1)) {
                return symbol;
            }
        }
        return null;
    }

    public int getFuncSize() {
        int size = 0;
        for (Symbol symbol : symbols) {
            size += symbol.getSize();
        }
        return size + MidcodeGenerator.getInstance().getPreSize();
    }

    public ArrayList<Symbol> getSymbols() {
        return symbols;
    }
}
